package com.example.myapplication_4

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Button
import android.widget.GridView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.myapplication_4.model.CardMatchingGame

class MainActivity : AppCompatActivity() {
    private lateinit var scoreTextView: TextView
    private lateinit var resetButton: Button
    private lateinit var exitButton: Button
    private lateinit var cardGridView: GridView

    private lateinit var game: CardMatchingGame
    private lateinit var cardAdapter: CardAdapter

    private var currentHighScore = 0 // 记录当前最高分

    companion object {
        private const val CARD_COUNT = 16
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initViews()
        setupClickListeners()
        initGame()
        loadCurrentHighScore() // 加载当前最高分
    }

    private fun initViews() {
        scoreTextView = findViewById(R.id.scoreTextView)
        resetButton = findViewById(R.id.resetButton)
        exitButton = findViewById(R.id.exitButton)
        cardGridView = findViewById(R.id.cardGridView)
    }

    private fun setupClickListeners() {
        resetButton.setOnClickListener {
            resetGame()
        }

        exitButton.setOnClickListener {
            // 退出前保存最高分
            saveAndUpdateHighScore(game.score)
            finish()
        }

        cardGridView.setOnItemClickListener { _, _, position, _ ->
            val previousScore = game.score // 记录点击前的分数
            game.chooseCardAtIndex(position)
            updateUI()

            // 只有当分数实际增加时才检查最高分
            if (game.score > previousScore) {
                checkAndUpdateHighScore()
            }

            // 检查游戏是否完成
            checkGameCompletion()
        }
    }

    private fun initGame() {
        game = CardMatchingGame(CARD_COUNT)
        cardAdapter = CardAdapter()
        cardGridView.adapter = cardAdapter
        updateUI()
    }

    // 加载当前最高分
    private fun loadCurrentHighScore() {
        val sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE)
        currentHighScore = sharedPreferences.getInt("highScore", 0)
    }

    private fun updateUI() {
        scoreTextView.text = "得分：${game.score}"
        cardAdapter.notifyDataSetChanged()
    }

    private fun resetGame() {
        // 重置前保存当前游戏的最高分
        saveAndUpdateHighScore(game.score)
        game = CardMatchingGame(CARD_COUNT)
        updateUI()
    }

    // 检查游戏是否完成
    private fun checkGameCompletion() {
        var allMatched = true
        for (i in 0 until game.getCardsCount()) {
            val card = game.cardAtIndex(i)
            if (!card.isMatched) {
                allMatched = false
                break
            }
        }

        if (allMatched) {
            // 游戏完成，显示完成消息
            showGameCompletionMessage()
        }
    }

    // 显示游戏完成消息
    private fun showGameCompletionMessage() {
        val message = if (game.score > currentHighScore) {
            "🎉 恭喜！刷新最高分：${game.score}"
        } else {
            "游戏完成！得分：${game.score}"
        }

        Toast.makeText(this, message, Toast.LENGTH_LONG).show()
    }

    // 保存并更新最高分到SharedPreferences
    private fun saveAndUpdateHighScore(currentScore: Int) {
        val sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE)
        val savedHighScore = sharedPreferences.getInt("highScore", 0)

        // 如果当前分数高于保存的最高分，更新最高分
        if (currentScore > savedHighScore) {
            sharedPreferences.edit().putInt("highScore", currentScore).apply()
            currentHighScore = currentScore // 更新本地记录

            // 只有在游戏进行中刷新最高分时才显示提示
            if (savedHighScore > 0) {
                Toast.makeText(this, "🎉 刷新最高分：$currentScore", Toast.LENGTH_SHORT).show()
            }
        }
    }

    // 检查并更新最高分（实时显示）
    private fun checkAndUpdateHighScore() {
        val sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE)
        val savedHighScore = sharedPreferences.getInt("highScore", 0)

        // 如果当前游戏分数超过了最高分，实时更新
        if (game.score > savedHighScore) {
            sharedPreferences.edit().putInt("highScore", game.score).apply()
            currentHighScore = game.score // 更新本地记录
        }
    }

    // 当Activity被销毁时保存最高分
    override fun onDestroy() {
        super.onDestroy()
        saveAndUpdateHighScore(game.score)
    }

    // 当Activity进入后台时保存最高分
    override fun onPause() {
        super.onPause()
        saveAndUpdateHighScore(game.score)
    }

    private inner class CardAdapter : BaseAdapter() {
        override fun getCount(): Int = game.getCardsCount()

        override fun getItem(position: Int): Any = game.cardAtIndex(position)

        override fun getItemId(position: Int): Long = position.toLong()

        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
            val view = convertView ?: layoutInflater.inflate(R.layout.card_item, parent, false)

            val cardBack = view.findViewById<TextView>(R.id.cardBack)
            val cardFront = view.findViewById<TextView>(R.id.cardFront)

            val card = getItem(position) as com.example.myapplication_4.model.Card

            if (card.isMatched) {
                cardBack.visibility = View.INVISIBLE
                cardFront.visibility = View.INVISIBLE
            } else if (card.isChosen) {
                cardBack.visibility = View.INVISIBLE
                cardFront.visibility = View.VISIBLE
                cardFront.text = card.toString()
            } else {
                cardBack.visibility = View.VISIBLE
                cardFront.visibility = View.INVISIBLE
            }

            return view
        }
    }
}